import React, { Component } from 'react';
import Styled from 'styled-components';
import { Table, Button, Upload, message } from 'antd';
import http from '@/utils/http';

const Box = Styled.div`
  padding: 24px 20px 0 20px;
  >.btnList {
    button {
      margin: 0 12px 12px 0;
    }     
  }
`;

class Grid extends Component {
  constructor(props) {
    super(props);
    this.state = {
      loading: false,
      uploadLoading: false,
      dataSource: [],
      pagingConfig: props.pagination === false ? false : this.setPagination(props.pagination || {}),
      operateBtns: props.operation ? this.setOperateBtns(props.operation) : []
    };
  }

  componentDidMount() {
    if (this.props.url) {
      const { current, pageSize } = this.state.pagingConfig;
      pageSize ? this.queryListByPaging(current, pageSize) : this.queryList();
    }
  }

  componentDidUpdate(prevProps) {
    const { url, search, operation } = this.props;
    if ((prevProps.search !== search && url) || prevProps.url !== url) {
      const { pageSize } = this.state.pagingConfig;
      pageSize ? this.queryListByPaging(1, pageSize) : this.queryList();
    }
    if (prevProps.operation !== operation && operation.length) {
      this.setState({ operateBtns: this.setOperateBtns(operation) });
    }
  }

  setOperateBtns(list) {
    const btnList = [];
    list.forEach(item => {
      if (item.state === 'add') {
        btnList.push(Object.assign({
          type: 'primary',
          icon: 'plus',
          title: '新增'
        }, item));
      } else if (item.state === 'upload') {
        const onChange = item.props.onChange;
        const props = Object.assign(item.props, {
          onChange: ({file, fileList}) => {
            if (file.status === 'uploading') {
              this.setState({ uploadLoading: true });
            } else if (file.status === 'done') {
              message.success(`${file.name} 文件上传成功！`);
              this.setState({ uploadLoading: false });
            } else if (file.status === 'error') {
              message.error(`${file.name} 文件上传失败！`);
              this.setState({ uploadLoading: false });
            }
            // eslint-disable-next-line
            onChange?.({file, fileList});
          }
        });
        btnList.push(Object.assign({
          icon: 'upload',
          title: '上传'
        }, item, { props }));
      } else {
        btnList.push(item);
      }
    });
    return btnList;
  }

  setPagination(data) {
    const onChange = data.onChange;
    const onShowSizeChange = data.onShowSizeChange;
    return Object.assign({
      showSizeChanger: true,
      showQuickJumper: true,
      pageSize: 10,
      current: 1,
      showTotal: (total, range) => `共 ${total} 条 当前显示 ${range[0]}-${range[1]} 条`
    }, data, {
      onChange: (current, pageSize) => {
        this.queryListByPaging(current, pageSize).then(() => {
          // eslint-disable-next-line
          onChange?.(current, pageSize);
        });
      },
      onShowSizeChange: (current, pageSize) => {
        this.queryListByPaging(current, pageSize).then(() => {
          // eslint-disable-next-line
          onShowSizeChange?.(current, pageSize);
        });
      }
    });
  }

  queryListByPaging(pn, ps) {
    this.setState({ loading: true });
    const { url, search } = this.props;
    return http.get(url, {params: { pn, ps, ...search }}).then(response => {
      const { rows, total } = response.data;
      this.setState({
        loading: false,
        dataSource: rows,
        pagingConfig: {
          current: pn,
          pageSize: ps,
          total
        }
      });
    });
  }

  queryList() {
    this.setState({ loading: true });
    const { url, search } = this.props;
    return http.get(url, {params: search}).then(response => {
      this.setState({
        loading: false,
        dataSource: response.data
      });
    });
  }

  // 若存在复选框，获取选中数据
  getSelectedData() {
    // return this.state.selectedList;
  }
  renderOperateBtns(i, idx) {
    if (i.state === 'upload') {
      const { uploadLoading } = this.state;
      return <Upload key={idx} {...i.props} ><Button type={i.type} icon={uploadLoading ? 'loading' : i.icon} disabled={uploadLoading}>{i.title}</Button></Upload>
    }else{
      return <Button key={idx} type={i.type} onClick={i.onClick} icon={i.icon}>{i.title}</Button>
    }
  }
  refreshGrid(isCurrent) {
    const { current, pageSize } = this.state.pagingConfig;
    pageSize ? this.queryListByPaging(isCurrent ? current : 1, pageSize) : this.queryList();
  }
  render() {
    const { loading, dataSource, pagingConfig, operateBtns } = this.state;
    const { url, search, operation, pagination, className, ...params } = this.props;
    return (
      <Box className={className}>
        <div className="btnList">
          {operateBtns.map((i, idx) => this.renderOperateBtns(i, idx))}
        </div>
        <Table className="rs-grid" rowKey="id" loading={loading} pagination={pagingConfig} dataSource={dataSource} {...params} />
      </Box>
    );
  }
}      

export default Grid;
